package com.kotlin.myapplication.mvp.presenter

import android.util.Log
import com.kotlin.myapplication.mvp.model.CalentarContract
import com.kotlin.myapplication.utils.Logger
import com.kotlin.myapplication.network.RetrofitUtil
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers

/**
 *@lil
 *@创建时间 2019/10/30 10:18
 *@描述
 */

class MainPresenter(val view: CalentarContract.view) : CalentarContract.Presonter {


    /**
     * 订阅管理
     */
    var compositeDisposable: CompositeDisposable

    /**
     * 初始化
     */
    init {
        view.presenter = this
        compositeDisposable = CompositeDisposable()
    }

    /**
     * 开启订阅
     */
    override fun subscribe() {

    }

    /**
     * 关闭订阅
     */
    override fun unsubscribe() {
        compositeDisposable.clear()
    }

    /**
     * 业务接口实现
     */
    override fun getCalentarDayData(date: String) {
        val disposable = RetrofitUtil
                .retrofitService
                .calentarDay(date, "933dc930886c8c0717607f9f8bae0b48")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ result ->
                    view.showCalentarDay(result)
                    Logger.log(result.toString())
                }, { error ->
                    view.error(error.message.toString())
                    Logger.log(error.message.toString())
                })

        compositeDisposable.add(disposable)
    }

    override fun getWeather(data: String) {

//        var code = URLEncoder.encode(date, "UTF-8")
//        Logger.log(code)
        Log.d("code", data)
        val disposable = RetrofitUtil
                .weatherService
                .getWeather(data, "793d00e1e829ecaa1bcdc29986854c86")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ result ->
                    view.showWeather(result)
                    Logger.log(result.toString())
                }, { error ->
                    view.error(error.message.toString())
                    Logger.log(error.message.toString())

                })

        compositeDisposable.add(disposable)


    }

    override fun getNews(type: String) {
        val disposable = RetrofitUtil
                .newService
                .getNews(type, "8b4a53a267107647a8584dfdb4f9d55e")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ result ->
                    view.showNews(result)
                    Logger.log(result.toString())
                }, { error ->
                    view.error(error.message.toString())
                    Logger.log(error.message.toString())

                })

        compositeDisposable.add(disposable)
    }




}